<?php

namespace shop\controllers;

use shop\components\WeChat;
use shop\service\WechatService;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class WechatController extends Controller
{
    public $enableCsrfValidation= false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 多个小程序进入此处进行注册，获取openid给用户发零钱提现
     * @return \yii\web\Response
     */
    public function actionLogin()
    {
        $request = Yii::$app->request;
        $code = $request->post('code');

        $appid = $request->post('appid');
        $uid = $request->post('uid');
        $mid = $request->post('mid');


        $msg = '';
        $flag = false;
        if (!$code) {
            $msg = 'code 不能为空';
        } elseif (!$appid) {
            $msg = 'appid 不能为空';
        } elseif (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$mid) {
            $msg = 'mid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {

            //判断商户是否存在
            if (!array_key_exists($mid, Yii::$app->params['serviceNum'])) {
                $jsonData = ResponseHelper::buildJsonData(400, '商家账号不存在,请联系商家或者开发者');
                return $this->asJson($jsonData);
            }


            $wxappid = Yii::$app->params['serviceNum'][$mid]['wxAppid'];
            $wxsecret = Yii::$app->params['serviceNum'][$mid]['wxSecret'];

            if ($appid != $wxappid) {
                $jsonData = ResponseHelper::buildJsonData(400, 'appid不一致');
                return $this->asJson($jsonData);
            }

            $WeChat = new WeChat($wxappid, $wxsecret);

            $data = $WeChat->wxLogin($code);

            if ($data && $data['result']) {
                //解密unionid
                if (!$data['data']['unionid']) {
                    if ($request->post('encryptedData')) {
                        $res = $WeChat->getDecryptData($data['data']['session_key'], $request->post('iv'), $request->post('encryptedData'));
                        if ($res && $res['result']) {
                            $data['data']['unionid'] = $res['data']['unionId'];
                        }
                    }
                }


                $wechatService = new WechatService();
                //查看用户是否已经入库
                $where = " uid = {$uid} AND mid = {$mid} AND appid = '{$appid}'";
                $user = $wechatService->userOne($where);
                $nickname = $request->post('nickname');
                $avatar_url = $request->post('avatar_url');
                $time = time();
                if (!$user) {
                    //将用户入库
                    $map = [
                        'nickname' => $nickname ? $nickname : '游客',
                        'openid' => $data['data']['openid'],
                        'unionid' => $data['data']['unionid'],
                        'avatar_url' => $avatar_url ? $avatar_url : 'https://teach-1258261086.cos.ap-guangzhou.myqcloud.com/image/admin/avatar/avatar_xiu.png',
                        'appid' => $appid,
                        'uid' => $uid,
                        'mid' => $mid,
                        'create_time' => $time,
                        'update_time' => $time,
                    ];

                    $result = $wechatService->registerUser($map);

                    if (!$result)  {
                        $jsonData = ResponseHelper::buildJsonData(400, '注册失败');
                        return $this->asJson($jsonData);
                    }

                } else {
                    //更新数据

                    $set = " update_time = '{$time}' ";
                    if ($nickname) {
                        $set .= " , nickname = '{$nickname}' ";
                    }
                    if ($avatar_url) {
                        $set .= " , avatar_url = '{$avatar_url}' ";
                    }
                    if ($data['data']['unionid']) {
                        $set .= " , unionid = '{$data['data']['unionid']}'";
                    }

                    $result = $wechatService->userUpdate($set, $where);
                    if (!$result) {
                        $jsonData = ResponseHelper::buildJsonData(400, '更新失败');
                        return $this->asJson($jsonData);
                    }

                }

            }
            $data['data']['id'] = $uid;
            $data['data']['appid'] = $appid;
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $data['data']);
        }

        return $this->asJson($jsonData);
    }
}